package com.hxzy.interceptor;

import com.hxzy.util.SSMThreadLocal;
import com.hxzy.util.TokenServiceUtil;
import com.hxzy.vo.AdminLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayDeque;

/**
 * 令牌验证拦截器
 *
 *
 * @author tonneyyy
 */
@Component
public class TokenValidateHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenServiceUtil  tokenServiceUtil;
    /**
     * 执行Controller方法之前做的事情
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwtToken=request.getHeader("Authorization");
        AdminLoginVO adminLoginVO = this.tokenServiceUtil.validatorToken(jwtToken);

        if(adminLoginVO!=null){
           //存在本地线程池，供后面的方法使用
            SSMThreadLocal.adminLoginVOThreadLocal.set(adminLoginVO);
            return true;
        }

        return false;
    }

    /**
     *  执行Controller之后做的事情
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
      //移出
        SSMThreadLocal.adminLoginVOThreadLocal.remove();
    }
}
